#!/usr/bin/env python3
"""
审计日志路由
"""

from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio.session import AsyncSession

from app.database.session import get_db
from app.schemas.audit_log import AuditLogListResponse, AuditLogResponse
from app.services.audit_service import get_audit_logs

router = APIRouter()


@router.get("/", response_model=AuditLogListResponse)
async def list_audit_logs(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    operator: str | None = Query(None, description="操作人过滤"),
    operation_type: str | None = Query(None, description="操作类型过滤"),
    start_time: datetime | None = Query(None, description="开始时间"),
    end_time: datetime | None = Query(None, description="结束时间"),
    db: AsyncSession = Depends(get_db),
):
    """
    获取审计日志列表

    Args:
        page: 页码
        page_size: 每页数量
        operator: 操作人过滤
        operation_type: 操作类型过滤
        start_time: 开始时间
        end_time: 结束时间
        db: 数据库会话

    Returns:
        AuditLogListResponse: 审计日志列表响应
    """
    try:
        logs, total = await get_audit_logs(
            db=db,
            page=page,
            page_size=page_size,
            operator=operator,
            operation_type=operation_type,
            start_time=start_time,
            end_time=end_time,
        )

        # 将AuditLog ORM模型转换为AuditLogResponse
        log_responses = [AuditLogResponse.model_validate(log) for log in logs]
        
        return AuditLogListResponse(
            data=log_responses, total=total, page=page, page_size=page_size, total_pages=(total + page_size - 1) // page_size
        )

    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"获取审计日志失败: {str(e)}")


@router.get("/{log_id}", response_model=AuditLogResponse)
async def get_audit_log(log_id: int, db: AsyncSession = Depends(get_db)):
    """
    获取单个审计日志

    Args:
        log_id: 日志ID
        db: 数据库会话

    Returns:
        AuditLogResponse: 审计日志响应
    """
    from sqlalchemy.future import select

    from app.models.audit_log import AuditLog

    try:
        result = await db.execute(select(AuditLog).where(AuditLog.id == log_id))
        log = result.scalar_one_or_none()

        if not log:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="审计日志不存在")

        return AuditLogResponse.model_validate(log)

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"获取审计日志失败: {str(e)}")
